package com.sky.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.constant.WXConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.po.UserPO;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.repository.UserRepository;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Content:
 * @Author: Asen
 * @Date: 2023/9/6 15:50
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserRepository userRepository;

    /**
     * 微信登录
     * @param source
     * @return
     */
    @Override
    public UserPO wxLogin(UserLoginDTO source) {
        //调用微信接口服务,获取当前微信用户的openid
        Map<String,String> map = new HashMap<>();
        map.put(WXConstant.APPID,weChatProperties.getAppid());
        map.put(WXConstant.SECRET,weChatProperties.getSecret());
        map.put(WXConstant.JS_CODE,source.getCode());
        map.put(WXConstant.GRANT_TYPE,WXConstant.AUTHORIZATION_CODE);
        //发送请求
        String result = HttpClientUtil.doGet(WXConstant.WX_LOGIN, map);
        //解析结果
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.getString(WXConstant.OPEN_ID);
        //是否已经注册
        UserPO userPO = userRepository.selectOne(new LambdaQueryWrapper<UserPO>()
                .eq(UserPO::getOpenid, openid)
                .last("limit 1"));
        if(ObjectUtil.isNull(userPO)){
            userPO = new UserPO();
            userPO.setOpenid(openid);
            userRepository.insert(userPO);
        }
        return userPO;
    }
}
